package com.it.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.entity.insure.AiFarmerInsured;
import com.it.entity.insure.AiInsureOrder;
import com.it.mapper.AiFarmerInsuredMapper;
import com.it.mapper.AiInsureOrderMapper;
import com.it.service.AiFarmerInsuredService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import utils.R;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AiFarmerInsuredServiceImpl extends ServiceImpl<AiFarmerInsuredMapper, AiFarmerInsured> implements AiFarmerInsuredService {

    private static final Logger log = LoggerFactory.getLogger(AiFarmerInsuredServiceImpl.class);

    @Autowired
    private AiFarmerInsuredMapper aiFarmerInsuredMapper;

    @Autowired
    private AiInsureOrderMapper insureOrderMapper;

    @Override
    @Transactional
    public R addOrUpdate(AiFarmerInsured aiFarmerInsured) {
        try {
            // 检查参数合法性
            if (aiFarmerInsured == null || !StringUtils.hasText(aiFarmerInsured.getPhone())) {
                return R.Failed("农户信息或手机号不能为空");
            }

            // 检查用户是否存在（通过手机号）
            LambdaQueryWrapper<AiFarmerInsured> qw = new LambdaQueryWrapper<>();
            qw.eq(AiFarmerInsured::getPhone, aiFarmerInsured.getPhone());
            AiFarmerInsured existingFarmer = aiFarmerInsuredMapper.selectOne(qw);

            // 存在该手机号对应的用户，执行更新操作
            if (existingFarmer != null) {
                aiFarmerInsured.setInsuredId(existingFarmer.getInsuredId());
                aiFarmerInsured.setUpdateTime(LocalDateTime.now());
                aiFarmerInsuredMapper.updateById(aiFarmerInsured);
                log.info("更新农户信息成功，insuredId: {}", existingFarmer.getInsuredId());
                return R.Success("农户信息更新成功", aiFarmerInsured.getInsuredId());
            } else {
                // 不存在该手机号对应的用户，执行新增操作
                aiFarmerInsured.setCreateTime(LocalDateTime.now());
                aiFarmerInsured.setUpdateTime(LocalDateTime.now());
                aiFarmerInsuredMapper.insert(aiFarmerInsured);

                // 获取自动生成的ID（确保实体类和数据库配置了自增）
                Integer newInsuredId = aiFarmerInsured.getInsuredId();
                log.info("新增农户信息成功，insuredId: {}", newInsuredId);
                return R.Success("新增农户信息成功", newInsuredId);
            }
        } catch (Exception e) {
            log.error("农户信息添加或更新失败", e);
            // 回滚事务
            throw e;
        }
    }
    /**
     * 根据农户手机号和姓名查询其所有保单信息
     * @param phone 手机号
     * @param name 姓名
     * @return 符合条件的所有保单信息列表，若未找到则返回空列表
     */
    @Override
    public R searchPolicy(String phone, String name) {

        // 参数校验
        if (phone == null && name == null) {
            return R.Failed("手机号和姓名不能为空");
        }

        // 1. 根据手机号和姓名查询农户信息，获取投保人ID
        LambdaQueryWrapper<AiFarmerInsured> qw = new LambdaQueryWrapper<>();
        if (phone != null && !phone.isEmpty()) {
            qw.eq(AiFarmerInsured::getPhone, phone);
        }
        qw.like(AiFarmerInsured::getInsuredName, name);
        //查询 获取到多个农户信息列表
        List<AiFarmerInsured> farmerInsureds = aiFarmerInsuredMapper.selectList(qw);

        // 提取所有有效农户的ID并去重
        List<Integer> insuredIds = farmerInsureds.stream()
                .map(AiFarmerInsured::getInsuredId)
                .distinct()
                .collect(Collectors.toList());

        // 2. 如果未找到对应的农户，返回空列表
        if (insuredIds.isEmpty()) {
            return R.Failed("无符合条件农户"); // 返回空列表而非null，避免NPE
        }

        // 3. 根据所有投保人ID查询所有保单信息
        LambdaQueryWrapper<AiInsureOrder> qw1 = new LambdaQueryWrapper<>();
        qw1.in(AiInsureOrder::getInsuredId, insuredIds)
                .eq(AiInsureOrder::getPolicyStatus,2) //过滤保单状态
                .orderByDesc(AiInsureOrder::getCreateTime); //按照创建时间排序

        List<AiInsureOrder> insureOrders = insureOrderMapper.selectList(qw1);
        // 4. 返回查询结果（可能为空列表）
        if (insureOrders.isEmpty()) {
            return R.Success("暂无保单信息");
        }

        return R.Success(insureOrders);
    }
}